/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testjava2d;

/**
 *
 * @author nicolas
 */
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.util.LinkedList;
import java.util.List;
import javax.swing.*;

public class JCanvas extends JPanel implements KeyListener {

    private List<VisitorSprite2D> visitors = new LinkedList<VisitorSprite2D>();
    private AffineTransform originAffineTransform = null;

    public JCanvas() {
        super();
        this.setOpaque(false);
        this.setBackground(Color.BLACK);
        addKeyListener(this);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g;
        List<VisitorSprite2D> visitorSamples = this.visitors;
        if (visitorSamples != null) {
            for (VisitorSprite2D vs : visitorSamples) {
                originAffineTransform = g2.getTransform();
                g2.setColor(vs.getColor());
                g2.translate(vs.getVisitor().getPosX(), vs.getVisitor().getPosZ());
                g2.rotate(Math.toRadians(vs.getVisitor().getRot()));
                //g2.fill(new Rectangle(new Dimension(30, 20)));
                
                g2.fill(vs.getShape());
                g2.setTransform(originAffineTransform);
            }
        }
    }

    public void addVisitor(VisitorSprite2D v) {
        visitors.add(v);
    }

    public VisitorSprite2D getVisitor() {
        return visitors.get(0);
    }

    public void keyTyped(KeyEvent arg0) {
    }

    public void keyPressed(KeyEvent arg0) {
        char key = arg0.getKeyChar();
        if (key == 'z') {
            //Move forward
            visitors.get(0).getVisitor().setPosX(visitors.get(0).getVisitor().getPosX() + Math.cos(Math.toRadians(visitors.get(0).getVisitor().getRot())));
            visitors.get(0).getVisitor().setPosZ(visitors.get(0).getVisitor().getPosZ() + Math.sin(Math.toRadians(visitors.get(0).getVisitor().getRot())));
            repaint();

        } else if (key == 'q') {
            //Turn left but center of rotation is not the center of the rectangle
            visitors.get(0).getVisitor().setRot(visitors.get(0).getVisitor().getRot() - 10);
            repaint();

        } else if (key == 'd') {
            //Turn right
            visitors.get(0).getVisitor().setRot(visitors.get(0).getVisitor().getRot() + 10);
            repaint();
        }
    }

    public void keyReleased(KeyEvent arg0) {
    }
}
